﻿#include "websocketserver.h"
#include <QHostAddress>

WebSocketServer::WebSocketServer(QObject *parent) : QObject{parent}
{
  m_socket = nullptr;
  m_server = new QWebSocketServer("server", QWebSocketServer::NonSecureMode, this);
  if (m_server->listen(QHostAddress::LocalHost, 8088))
  {
    connect(m_server, &QWebSocketServer::newConnection, this, &WebSocketServer::onNewConnection);
  }
}

WebSocketServer::~WebSocketServer()
{
  onDisconnected();
  if (nullptr != m_server)
  {
    m_server->disconnect();
    m_server->close();
    delete m_server;
    m_server = nullptr;
  }
}

void WebSocketServer::onNewConnection(void)
{
  qDebug() << "onNewConnection";
  if (nullptr != m_server)
  {
    onDisconnected();
    m_socket = m_server->nextPendingConnection();
    if (nullptr != m_socket)
    {
      connect(m_socket, &QWebSocket::disconnected, this, &WebSocketServer::onDisconnected);
      connect(m_socket, &QWebSocket::textMessageReceived, this,
              [=](const QString &msg)
              {
                emit msgReceived(msg);
                qDebug() << msg;
              });
      connect(m_socket, &QWebSocket::binaryMessageReceived, this,
              [=](const QByteArray &msg)
              {
                emit msgReceived(msg);
                qDebug() << msg;
              });
      connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this,
              SLOT(onErrorOccurred(QAbstractSocket::SocketError)));
    }
  }
}

void WebSocketServer::onDisconnected()
{
  if (nullptr != m_socket)
  {
    m_socket->disconnect();
    delete m_socket;
    m_socket = nullptr;
  }
}

void WebSocketServer::onErrorOccurred(QAbstractSocket::SocketError socketError)
{
  qDebug() << QString("Websocketserver error(%1): ").arg(socketError) << m_socket->errorString();
}